package dbb

import (
	"context"
	"embed"
	"strings"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/util/gconv"
	octicons "github.com/lusingander/fyne-octicons"
	"github.com/y2h/fyne_poem/menu"
	"github.com/y2h/fyne_poem/themee"
	"github.com/y2h/fyne_poem/util"
	"xorm.io/xorm/schemas"
)

func Run(srcs embed.FS) {
	Me = New("io.fyne.demo", "Database Manager数据库管理(sqlite)")
	Me.Default()

	defer func() {
		// if newDb != nil {
		// 	newDb.Close(newDb.GetCtx())
		// }
	}()

	cc := container.NewHSplit(Me.Dbtree, Me.Tabs)
	cc.Offset = 0.2
	tb := widget.NewToolbar(
		newcon(),
		importSql(),
		toFile(),
		widget.NewToolbarAction(theme.GridIcon(), func() {
			sqlui(Me.Db)
		}),
		widget.NewToolbarAction(theme.InfoIcon(), func() {
			GenStruct(Me.Db, Me.CurrentTbl, Me.Tabs, Me.Msg)
		}),
	)

	btn := widget.NewButton("Connect", func() {
		connect()
	})
	top := container.NewVBox(tb,
		container.NewBorder(nil, nil, nil, btn,
			NewOpenFile(Me.DbPath, Me.W)),
	)

	c := container.NewBorder(top, Me.Msg, nil, nil, cc)
	Me.W.SetContent(c)
	Me.W.SetMainMenu(menu.MainMenuu(srcs, Me.A))

	Me.W.Resize(fyne.NewSize(900, 700))
	Me.W.SetMaster()
	Me.W.SetCloseIntercept(func() {
		dialog.ShowConfirm("Closing...", "Are you sure to close?",
			func(b bool) {
				if b {
					Me.W.Close()
					if Me.Db != nil {
						Me.Db.Close(Me.Ctx)
					}
				}
			}, Me.W)
	})
	Me.W.ShowAndRun()
}
func New(appid, wname string) *YhDB {
	a := app.NewWithID(appid)
	w := a.NewWindow(wname)
	a.Settings().SetTheme(&themee.MyTheme{})
	a.SetIcon(octicons.DatabaseIcon())

	return &YhDB{A: a, W: w}
}
func (me *YhDB) Default() *YhDB {
	// if Me.Msg != nil {
	// 	return me
	// }

	Me.D = fyne.CurrentApp().Driver()
	menu.SetGlog()
	me.Tblsm = make(map[string]*schemas.Table)
	me.DbPath = binding.NewString()
	bdddl = binding.NewString()
	me.DbPath.Set("./quantangshi.db")
	me.Msg = widget.NewLabel("")
	me.Dbtree = widget.NewTree(nil, nil, nil, nil)
	me.Dbtree.OnSelected = func(uid widget.TreeNodeID) {
		v, _ := garray.NewStrArrayFrom(strings.Split(uid, "/")).PopRight()
		if Me.Tbls.Contains(v) {
			count, _ := Me.Db.Model(v).Count()
			me.Msg.SetText("共" + gconv.String(count) + "条纪录")
			me.CurrentTbl = v
		} else {
			me.Msg.SetText(v)

			if util.IsInSlice(v, dbs.Keys()) {
				me.Db = dbs.Get(v).(gdb.DB)
				me.Name = v
				tbls, _ := me.Db.Tables(me.Ctx)
				me.Tbls = garray.NewStrArrayFrom(tbls)
			}
		}
	}
	Me.Tabs = container.NewDocTabs()
	Me.Tabs.SetTabLocation(container.TabLocationBottom)
	return me
}

var Me *YhDB

type YhDB struct {
	Name       string // 当前数据库名称
	Db         gdb.DB
	CurrentTbl string
	// Tbls       []string
	Tbls      *garray.StrArray // 当前数据库的所有表名
	Tblsm     map[string]*schemas.Table
	Ctx       context.Context
	BdNumTbls binding.Int
	// 数据库路径
	DbPath    binding.String
	A         fyne.App
	W         fyne.Window
	D         fyne.Driver
	// 表数据列表
	DataList  *widget.List
	Msg       *widget.Label
	Dbtree    *widget.Tree
	Tabs      *container.DocTabs
	Err       error
}
